<?php

if ( "on" == get_site_option( 'bpdev-subscribe-status' ) ) {

	add_action( 'publish_post', 'bpdev_subscribe_notification_new_post', 1, 1 );
	add_action( 'bp_notification_settings', 'bpdev_subscribe_notification_settings', 2 );

}

function bpdev_subscribe_notification_new_post( $post_id ) {

	global $bp, $current_blog;

	$users = BPDEV_Subscribe::get_blog( $current_blog->blog_id );

	if ( !is_array( $users ) ) {

		$users = array( $users );

	} else {

		foreach ( $users as $user ) {

			if ( BPDEV_Subscribe::check( $user, $current_blog->blog_id ) ) {

				$ud = get_userdata( $user );
				if ( 'yes' == get_usermeta( $user, 'notification_subscribe_post' ) || !get_usermeta( $user, 'notification_subscribe_post' ) ) {
					$sender_name = get_blog_option( $current_blog->blog_id, 'blogname' );
					$post = get_blog_post( $current_blog->blog_id, $post_id );
					$post_content = apply_filters( 'the_excerpt', $post->post_content );
					$to = $ud->user_email;
					$subject = '[' . get_blog_option( 1, 'blogname' ) . '] ' . sprintf( __( 'New post on "%s"', 'buddypress' ), stripslashes($sender_name) );
					$permalink = get_blog_permalink( $current_blog->blog_id, $post_id );
					$settings_link = site_url() . '/' . MEMBERS_SLUG . '/' . $ud->user_login . '/settings/notifications';


					$message = sprintf( __( 
'%s has just published a new blog post:

"%s"

"%s"

Read the post here: %s

---------------------
',
					'buddypress' ), $sender_name, stripslashes( strip_tags( $post->post_title ) ),  strip_tags($post_content), $permalink );

					$message .= sprintf( __( 'To disable these notifications please log in and go to: %s', 'buddypress' ), $settings_link );

					// Send it
					wp_mail( $to, $subject, $message );
				}
			}
		}
	}
}

function bpdev_subscribe_notification_settings() {

	global $current_user;

	?>

	<table class="notification-settings" id="subscribe-notification-settings">
		<tr>
			<th class="icon"></th>
			<th class="title"><?php _e( 'Subscription', 'buddypress' ) ?></th>
			<th class="yes"><?php _e( 'Yes', 'buddypress' ) ?></th>
			<th class="no"><?php _e( 'No', 'buddypress' )?></th>
		</tr>
		<tr>
			<td></td>
			<td><?php _e( 'A blog post an article', 'buddypress' ) ?></td>
			<td class="yes"><input type="radio" name="notifications[notification_subscribe_post]" value="yes" <?php if ( !get_usermeta( $current_user->id, 'notification_subscribe_post' ) || 'yes' == get_usermeta( $current_user->id, 'notification_subscribe_new_message' ) ) { ?>checked="checked" <?php } ?>/></td>
			<td class="no"><input type="radio" name="notifications[notification_subscribe_post]" value="no" <?php if ( 'no' == get_usermeta( $current_user->id, 'notification_subscribe_post' ) ) { ?>checked="checked" <?php } ?>/></td>
		</tr>
		<?php do_action( 'subscribe_screen_notification_settings' ) ?>
	</table>

	<?php	

}

?>